package thread.juc.lock;

import lombok.NonNull;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ProductAndConsumerLock {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        Productor productor = new Productor(clerk);
        Consumer consumer = new Consumer(clerk);
        new Thread(productor, "生产者A").start();
        new Thread(consumer, "消费者B").start();
        new Thread(productor, "生产者C").start();
        new Thread(consumer, "消费者D").start();
    }
}

class ConsumerLock implements Runnable {
    @NonNull
    private Clerk clerk;

    public ConsumerLock(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            clerk.sale();
        }
    }
}

//店员
class ClerkLock {
    private int product = 0;

    Lock lock = new ReentrantLock();

    Condition condition = lock.newCondition();

    //进货
    public void get() {
//        if (product >= 1) {
        lock.lock();
        try {
            while (product >= 1) {
                System.out.println("产品已满!");
                try {
                    condition.await();
                } catch (InterruptedException e) {
                }
            }
            System.out.println(Thread.currentThread().getName() + ":" + ++product);
            condition.signalAll();//可以卖货
        } finally {
            lock.unlock();
        }
    }

    //卖货
    public void sale() {
        lock.lock();
        try {
            while (product <= 0) {//变成1 this.wait();就一直等待，所以去掉else 上面↑
                System.out.println("缺货了!");
                try {
                    condition.await();//不许消费
                } catch (InterruptedException e) {
                }
            }
            System.out.println(Thread.currentThread().getName() + ":" + --product);
            condition.signalAll();//有空位,可以补货
        } finally {
            lock.unlock();
        }
    }
}
